//
//  SchoolCLOViewController.m
//  ArtWalker
//
//  Created by Mac Jc on 15/8/4.
//  Copyright (c) 2015年 Mac Jc. All rights reserved.
//

#import "SchoolCLOViewController.h"
#import "AllHeader.h"
#import "StudioDetailViewController.h"
#import "CollegeDetailViewController.h"
#import <AFNetworking.h>
#import "SchoolViewController.h"
#import "StudioViewController.h"
#import "SearchSpaceViewController.h"
#import "AreaModel.h"
#import "SpaceModel.h"

#import "FMDB.h"

// 高校和画室的地区请求网址
#define areaURL @"http://arts1.dlab.com.cn/app/area"



@interface SchoolCLOViewController ()<UISearchBarDelegate>

//// 纵向滑动的collectionview 更新数据后可以分别展现高校和画室的页面
//@property (nonatomic ,strong) UICollectionView *collectionView;

// 高校页面
@property (nonatomic, strong) SchoolViewController *schoolVC;

// 画室页面
@property (nonatomic, strong) StudioViewController *studieVC;

// 标记当前展示的内容是高校还是画室，同时作为搜索的请求参数
@property (nonatomic, strong) NSString *type;

// 高校或画室搜索中的搜索框的输入内容
@property (nonatomic, strong) NSString *search;

// 搜索页面
@property (nonatomic, strong) SearchSpaceViewController *searchVC;

// 高校和画室切换控件
@property (nonatomic, strong) UISegmentedControl *segment;

// 存储地区的高校数组
@property (nonatomic, strong) NSMutableArray *schAreaArray;

// 存储地区的画室数组
@property (nonatomic, strong) NSMutableArray *stuAreaArray;

// 数据库
@property (nonatomic, strong) FMDatabase *db;

// 搞校和画室数据对应的数组，存放了字典，每个字典有两个键值对，分别对应得是地区和高校或画室，key 分别为 area 和 space

@end

@implementation SchoolCLOViewController


- (NSMutableArray *)schAreaArray{
    if (!_schAreaArray) {
        AreaModel *area = [[AreaModel alloc] init];
        area.place = @"九大美院";
        self.schAreaArray = [NSMutableArray arrayWithObject:area];
    }
    return _schAreaArray;
}

- (NSMutableArray *)stuAreaArray{
    if (!_stuAreaArray) {
        AreaModel *area = [[AreaModel alloc] init];
        area.place = @"推荐";
        self.stuAreaArray = [NSMutableArray arrayWithObject:area];
    }
    return _stuAreaArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = YES;

    self.view.backgroundColor = kBackgroundColor;
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    [self createFMDB];
    
    // 获取数据
    [self obtainDataForArea];
    
    [self createStudioView];
    [self createSchoolView];
    
    
    // 创建navigation视图
    [self createNavigationView];
    _type = @"高校";
}

- (void)obtainDataForArea{
    NSMutableArray *marr = [self searchDataModelFromDB];
    if (marr.count) {
        for (AreaModel *model in marr) {
            [self.schAreaArray addObject:model];
            [self.stuAreaArray addObject:model];
        }
         _studieVC.areaArr = _stuAreaArray;
         _schoolVC.areaArr = _schAreaArray;
    } else {
            [self requestData];
    }
}

// 高校和画室的地区请求
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manage POST:areaURL parameters:nil
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         // status 的值为1时，操作成功，可以使用数据
         NSInteger status = [dic[@"status"] integerValue];
         if (status == 1) {
             NSArray *areaArr = dic[@"list"];
             for (NSDictionary *areadic in areaArr) {
                 AreaModel *area = [[AreaModel alloc] init];
                 [area setValuesForKeysWithDictionary:areadic];
                 [self addDataIntoDataBase:area];
                 
                 [self.schAreaArray addObject:area];
                 [self.stuAreaArray addObject:area];
             }
         }
         NSLog(@"地区请求数据 ： %@",dic);
         dispatch_async(dispatch_get_main_queue(), ^{
             _schoolVC.areaArr = _schAreaArray;
         });
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
}

#pragma mark ---- 利用FMDB，进行本地数据持久化
// 创建数据库
- (void)createFMDB{
    NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"ARTS_FMDB.db"];
    NSLog(@"数据库 dbPath :%@",dbPath);
    self.db = [FMDatabase databaseWithPath:dbPath];
    
    if (![_db open]) {
        return;
    }
    /**
     *  在数据库db中，创建表Arealist
     */
    if(![_db tableExists:@"Arealist"]){
        [_db executeUpdate:@"CREATE TABLE Arealist (area_Id text primary key,place text, backImg text)"];
    }
}

// 向数据库中添加数据
- (void)addDataIntoDataBase:(AreaModel *)model{
    [_db executeUpdate:@"INSERT INTO Arealist (area_Id, place, backImg) VALUES (?,?,?)",model.area_Id,model.place,model.backImg];
}

// 从数据库中获取数据
- (NSMutableArray *)searchDataModelFromDB{
    NSMutableArray *marr = [NSMutableArray array];
    NSString *query = @"SELECT * FROM Arealist";
    FMResultSet * rs = [_db executeQuery:query];
    
    while ([rs next]) {
        AreaModel *model = [[AreaModel alloc] init];
        model.area_Id = [rs stringForColumn:@"area_Id"];
        model.place = [rs stringForColumn:@"place"];
        model.backImg = [rs stringForColumn:@"backImg"];
        [marr addObject:model];
    }
    [rs close];
    return marr;
}

// 从数据库中删除某个特定的数据
- (void)deleteDataFromDB{
    [_db executeUpdate:@"delete from Arealist"];
}

#pragma mark -- searcgBar
- (void)createNavigationView{
    // 自定义navigationview
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    whiteView.backgroundColor = [UIColor whiteColor];
    
    // 控制画室和高效切换的segmentControl
    _segment = [[UISegmentedControl alloc] initWithItems:@[@"高校",@"画室"]];
    _segment.frame = CGRectMake(SCREEN_WIDTH / 2 - 110, 25, 220, 30);
    _segment.tintColor  = kCustomColor(40, 40, 50, 1);
    _segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(doTopSegment:) forControlEvents:
     UIControlEventValueChanged];
    [whiteView addSubview:_segment];
    
    // navigationview 右侧的搜索图标添加手势
    UITapGestureRecognizer *tapgesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickSearch)];
    
    // navigationview 右侧的搜索图标
    UIImageView * searchView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH + _segment.right) /2.0 - 11, 27, 22, 22)];
    searchView.userInteractionEnabled = YES;
    searchView.image = [UIImage imageNamed:@"Search.png"];
    searchView.backgroundColor = [UIColor clearColor];
    [searchView addGestureRecognizer:tapgesture];
    [whiteView addSubview:searchView];
    
     //  横向滑动视图上方的浅色线
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 63.5, SCREEN_WIDTH, 0.5)];
    lineview.backgroundColor = kCustomColor(150, 150, 150, 1);
    lineview.alpha = 0.5;
    [whiteView addSubview:lineview];
    
    [self.view addSubview:whiteView];
   
}

// 控制画室和高效切换的segmentControl的点击事件
- (void)doTopSegment:(UISegmentedControl *)segment
{
    NSInteger index = segment.selectedSegmentIndex;
    if (index == 0) {
        /**
         *  将_schoolVC.view提到 self.view的最上层
         */
        [self.view bringSubviewToFront:_schoolVC.view];
        _type = @"高校";
    } else {
        [self.view bringSubviewToFront:_studieVC.view];
        _type = @"画室";
    }
}

/**
 * 搜索事件
 */

- (void)clickSearch{
    /**
     创建并且跳转到搜索页面
     */
    _searchVC = [[SearchSpaceViewController alloc] init];
    _searchVC.type = _type;
    [self.view addSubview:_searchVC.view];
    
    /**
     *  搜索结果的页面的点击事件，进入搜索详情页面
     */
    __weak SchoolCLOViewController *wSchoolVC = self;
    _searchVC.searchSpaceBlock = ^(NSMutableArray *arr){
        /**
         *  移除搜索页面和试图控制器
         */
        [wSchoolVC.searchVC.view removeFromSuperview];
        [wSchoolVC.searchVC removeFromParentViewController];
        
        NSString *type = [arr firstObject];
        NSString *ID = [arr lastObject];
        
        if ([type isEqualToString:@"高校"]) {
            CollegeDetailViewController *collegeDVC = [[CollegeDetailViewController alloc] init];
            collegeDVC.ID = ID;
            [wSchoolVC.navigationController pushViewController:collegeDVC animated:YES];
        } else {
            StudioDetailViewController *studioDVC = [[StudioDetailViewController alloc] init];
            studioDVC.space_ID = ID;
            [wSchoolVC.navigationController pushViewController:studioDVC animated:YES];
        }
    };
}

/**
 *  创建高校页面
 */
- (void)createSchoolView{
    _schoolVC = [[SchoolViewController alloc] init];
    _schoolVC.areaArr = _schAreaArray;
    [self.view addSubview:_schoolVC.view];
    
    _schoolVC.view.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 113);
    _schoolVC.collectionView.frame = CGRectMake(0, (SCREEN_WIDTH - 5 * 10) /  4 + 10, SCREEN_WIDTH, SCREEN_HEIGHT -(SCREEN_WIDTH - 5 * 10)/4 - 123);
}

// 创建画室页面
- (void)createStudioView{
    _studieVC = [[StudioViewController alloc] init];
    _studieVC.areaArr = _stuAreaArray;
    [self.view addSubview:_studieVC.view];
//    _studieVC.view.backgroundColor = kBackgroundColor;
    _studieVC.view.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 113);
    _studieVC.collectionView.frame = CGRectMake(0, (SCREEN_WIDTH - 5 * 10) /  4 + 10, SCREEN_WIDTH, SCREEN_HEIGHT -(SCREEN_WIDTH - 5 * 10)/4 - 123);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
